<template>
  <a-tree-select
    show-search
    ref="select"
    v-model:value="deptId"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="Please select"
    allow-clear
    tree-default-expand-all
    :tree-data="deptOpts"
    :fieldNames="{
      children: 'children',
      label: 'deptName',
      key: 'id',
      value: 'id',
    }"
    @select="handleSelect"
  >
  </a-tree-select>
</template>
<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  defineEmits,
  watch,
} from "vue";
import ResultEnum from "@/config/ResultEnum";
import { message } from "ant-design-vue";
import { copyObjVal } from "@/utils/common";
import { PlusOutlined } from "@ant-design/icons-vue";
import request from "@/request";

export default defineComponent({
  components: {
    PlusOutlined,
  },
  props: {
    version: {
      type: String,
    },
    deptId: {
      type: String,
    },
  },
  setup(props, context) {
    watch(
      () => props.version,
      (newVal: any, oldVal: any) => {
        loadData();
      }
    );

    watch(
      () => props.deptId,
      (newVal: any, oldVal: any) => {
        deptId.value = newVal;
      }
    );

    const deptId = ref("");
    const deptOpts = ref([]);
    const currNode = ref({} as any);

    const init = (val: string) => {
      deptId.value = val;
      currNode.value.id = val;
    };

    const getData = () => {
      return currNode.value.id == null || currNode.value.id == undefined
        ? null
        : currNode.value;
    };

    onMounted(() => {
      loadData();
    });

    const loadData = () => {
      request({
        url: "/dept/tree",
        method: "get",
      }).then((res: any) => {
        if (res.code == ResultEnum.SUCCESS_CODE) {
          console.log(res.result);
          deptOpts.value = res.result;
        } else {
          message.error(res.message);
        }
      });
    };

    const handleSelect = (value: any, node: any, extra: any) => {
      currNode.value = node;
    };

    return {
      init,
      getData,
      deptId,
      deptOpts,
      handleSelect,
    };
  },
});
</script>
